package experimental;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.ArrayList;

public class ConvertToCollinsParsable {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		//Need to remove the generated files ".col" in order to run it.
		
		String directoryName = "/home/pjbarrio/Dataset/ACE2003/ace_phase2/data/train/";
		
		File directory = new File(directoryName);
		
		File[] files = directory.listFiles();
		
		removeColFiles(files);
		
		ArrayList<File> errors = new ArrayList<File>();
		
		for (File file : files) {
			
			if (isPosFile(file)){
			
				int code = generateCollinsParseable(file);
				
				if (code != 0){
					errors.add(file);
				}

			}
		
		}

		for (File file : errors) {
			System.err.println("ERROR: " + file.getAbsolutePath());
		}
		
	}

	private static void removeColFiles(File[] files) {

		for (File file : files) {
			
			if (isColFile(file)){
				file.delete();
			}
			
		}
		
	}

	private static boolean isColFile(File file) {
		return (file.getName().endsWith(".col"));
	}

	private static boolean isPosFile(File file) {
		
		return (file.getName().endsWith(".pos"));
		
	}

	private static int generateCollinsParseable(File file) {
		
		Runtime rt = Runtime.getRuntime();
		
		try {
			Process pr = rt.exec(generateCommandLine(file));
			
			BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
			
			String line = null;
			
			System.setOut(new PrintStream(new File(file.getAbsolutePath().replaceAll(".pos", ".filter"))));
			
			while ((line = input.readLine()) != null){
				
				System.out.println(line);
				
			}
			
			int exitVal = pr.waitFor();
			
			System.err.println("Exited with error code " + exitVal);
			
			return exitVal;
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return 0;
		
	}

	private static String generateCommandLine(File file) {
		
		return "perl /home/pjbarrio/Software/Senseval/parseSenseval/ColinPrep.pl 119 " + file.getAbsolutePath().replaceAll(".pos", ".col") + " " + file.getAbsolutePath();
		
	}

}
